package cn.signalpha.modules.com.service;

import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.com.entity.UserLevelLog;
import cn.signalpha.modules.com.mapper.UserLevelLogMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 服务类
 *
 * @author signalpha
 */
@Service
public class UserLevelLogService extends ServiceImpl<UserLevelLogMapper, UserLevelLog> {

    /**
	 * 自定义Wrappers
	 */
    public QueryWrapper<UserLevelLog> selectUserLevelLogWrapper(Map<String, Object> params) {
        QueryWrapper<UserLevelLog> wrapper = Wrappers.query();
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("userId")), UserLevelLog::getUserId, params.get("userId"));
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("sourceId")), UserLevelLog::getSourceId, params.get("sourceId"));
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("sourceType")), UserLevelLog::getSourceType, params.get("sourceType"));
		wrapper.lambda().ge(ObjectUtil.isNotEmpty(params.get("createTimeBegin")), UserLevelLog::getCreateTime, params.get("createTimeBegin"));
		wrapper.lambda().le(ObjectUtil.isNotEmpty(params.get("createTimeEnd")), UserLevelLog::getCreateTime, params.get("createTimeEnd"));
        wrapper.lambda().orderByDesc(UserLevelLog::getId);
        return wrapper;
    }

	/**
	 * 订单金额统计
	 */
	public Integer sumByParams(Map<String, Object> params) {
		return sumByParams(params, "amount");
	}

	/**
	 * 订单金额统计
	 */
	public Integer sumByParams(Map<String, Object> params, String field) {
		QueryWrapper<UserLevelLog> wrapper = selectUserLevelLogWrapper(params);
		wrapper.select(StringUtil.format("ifnull(sum({}),0) as total", field));
		return Integer.valueOf(getMap(wrapper).get("total").toString());
	}

	/**
	 * 订单数量统计
	 */
	public long countByParams(Map<String, Object> params) {
		return count(selectUserLevelLogWrapper(params));
	}

}

